package com.example.demo6.ui.edit;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;

import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.demo6.Account;
import com.example.demo6.R;
import com.example.demo6.SQLite.LostGoods;
import com.example.demo6.SQLite.LostGoodsDao;
import com.example.demo6.SQLite.MyDatabase;

public class BlankFragment extends Fragment {

    String username;
    private EditText editLostItem, editLostPlace, editLoser, editLoserPhone, editLostTime, editLostItemDetail;
    private Button LostUpdateBtn,LostExit;
    private LostGoodsDao lostGoodsDao;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_blank, container, false);
        initViews(view);
        initDatabase(); // 初始化数据库

        editLoser.setText(Account.getInstance().getCurrentUsername());
        LostUpdateBtn.setOnClickListener(v -> {
            // Check if all required fields are filled before proceeding
            if (isInputValid()) {
                String lostGoods = editLostItem.getText().toString().trim();
                String loser = editLoser.getText().toString().trim();
                String lostPlace = editLostPlace.getText().toString().trim();
                String lostTime = editLostTime.getText().toString().trim();
                String loserPhone = editLoserPhone.getText().toString().trim();
                String lostDetail = editLostItemDetail.getText().toString().trim();

                LostGoods newItem = new LostGoods(lostGoods, loser, lostPlace, lostTime, loserPhone, lostDetail);
                new BlankFragment.InsertLostGoodsTask(getActivity(), lostGoodsDao).execute(newItem);
            }
        });
        Button LostExit = view.findViewById(R.id.LostExit);
        LostExit.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                navigateTo(R.id.navigation_home);
            }
        });

        return view;
    }

    private void navigateToLogin() {
        NavController navController = Navigation.findNavController(requireView());
        navController.navigate(R.id.loginFragment);
    }

    // 为了简化导航操作，可以创建一个辅助方法
    private void navigateTo(int destinationId) {
        NavController navController = Navigation.findNavController(requireView());
        Bundle bundle=new Bundle();
        bundle.putString("username", username);//传参
        navController.navigate(destinationId,bundle);
    }


    private boolean isInputValid() {
        if (editLostItem == null || editLoser == null) {
            Log.e("InputCheck", "One or more input fields are null.");
            return false;
        }

        String lostGoods = editLostItem.getText().toString().trim();
        String loser = editLoser.getText().toString().trim();

        if (TextUtils.isEmpty(lostGoods) || TextUtils.isEmpty(loser)) {
            Toast.makeText(getActivity(), "物品名称和失主姓名不能为空", Toast.LENGTH_SHORT).show();
            return false;
        }

        return true;
    }

    private void initViews(View view) {
        editLostItem = view.findViewById(R.id.editLostItem);
        editLostPlace = view.findViewById(R.id.editLostPlace);
        editLoser = view.findViewById(R.id.editLoser);
        editLoserPhone = view.findViewById(R.id.editLoserPhone);
        editLostTime = view.findViewById(R.id.editLostTime);
        editLostItemDetail = view.findViewById(R.id.editLostItemDetail);
        LostUpdateBtn = view.findViewById(R.id.LostUpdateBtn);
    }

    private void initDatabase() {
        MyDatabase db = MyDatabase.getInstance(getContext());
        lostGoodsDao = db.lostGoodsDao();
        if (lostGoodsDao == null) {
            Log.e("DatabaseInit", "LostGoodsDao is null.");
        }
    }
    // Async Task for inserting data into the database
    private static class InsertLostGoodsTask extends AsyncTask<LostGoods, Void, Void> {
        private final LostGoodsDao dao;
        private final Activity activity;

        InsertLostGoodsTask(Activity activity, LostGoodsDao dao) {
            this.activity = activity;
            this.dao = dao;
        }

        @Override
        protected Void doInBackground(LostGoods... lostGoods) {
            LostGoods item = lostGoods[0];
            dao.insertLostGoods(item); // Assuming 'insert' is a method in LostGoodsDao that handles the insertion.
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            Toast.makeText(activity, "添加成功", Toast.LENGTH_SHORT).show();
            NavController navController = Navigation.findNavController(activity, R.id.nav_host_fragment_activity_main);
            navController.navigate(R.id.loseFragment);
        }
    }
}